using System;
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Windows.Forms;

namespace Smallpointer.Configuration.Common
{
    public class ConfigurationReader : IDisposable
    {
        public ConfigurationReader()
        {
            MyConfiguration = HttpContext.Current != null ? WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath) : ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
        }

        public System.Configuration.Configuration MyConfiguration { get; private set; }
        public string Appsettings(string key)
        {
            var appsetting = MyConfiguration.AppSettings.Settings[key];
            return appsetting != null ? appsetting.Value : string.Empty;
        }

        public void UpdateKey(string key, string value)
        {
            if (MyConfiguration.AppSettings.Settings[key] != null)
            {
                MyConfiguration.AppSettings.Settings[key].Value = value;
            }
            else
            {
                MyConfiguration.AppSettings.Settings.Add(key, value);
            }
            MyConfiguration.Save(ConfigurationSaveMode.Modified);
        }

        #region IDisposable Members

        public void Dispose()
        {
            MyConfiguration = null;
        }

        #endregion
    }
}